package com.eternal.peaceworld.service;

/**
 * @ClassName AesEncryptorService
 * @PackageName encryptorspringbootautoconfigure.com.eternal.peaceworld.core
 * @projectName encryptor-spring-boot-parent
 * @Description TODO
 * @Author games
 * @Date 2025/8/17 下午12:40
 * @Version 1.0
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AesEncryptorService extends AbstractEncryptorService {

    private static final Logger logger = LoggerFactory.getLogger(AesEncryptorService.class);
    private final SecretKeySpec keySpec;

    public AesEncryptorService(String key) {
        if (key == null || key.length() != 16) {
            logger.error("无效的AES密钥: {}", key);
            throw new IllegalArgumentException("AES 密钥必须是 16 位");
        }
        this.keySpec = new SecretKeySpec(toBytes(key), "AES");
        logger.debug("AES加密服务初始化完成，密钥长度: {}", key.length());
    }

    @Override
    protected String doEncrypt(String plainText) {
        try {
            logger.debug("开始加密文本，长度: {}", plainText.length());
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] encrypted = cipher.doFinal(toBytes(plainText));
            String result = base64Encode(encrypted);
            logger.debug("加密完成，结果长度: {}", result.length());
            return result;
        } catch (Exception e) {
            logger.error("加密过程中发生错误", e);
            throw new RuntimeException("AES加密失败", e);
        }
    }

    @Override
    protected String doDecrypt(String encryptedText) {
        try {
            logger.debug("开始解密文本，长度: {}", encryptedText.length());
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] decoded = base64Decode(encryptedText);
            byte[] decrypted = cipher.doFinal(decoded);
            String result = toString(decrypted);
            logger.debug("解密完成，结果长度: {}", result.length());
            return result;
        } catch (Exception e) {
            logger.error("解密过程中发生错误", e);
            throw new RuntimeException("AES解密失败", e);
        }
    }
}